<template>
  <div id="home">
    <div class="container-xl">
      <div class="row">
        <div class="col-md-8 col-sm-12">
          <div class="my-home-div">
            <div :style="{ minHeight: '343px', paddingBottom: '12px' }">
              <div class="row my-home-div-line">
                <div class="col">
                  <i class="icon icon-ic_fluent_flag_16_filled"></i> 近期比赛
                </div>
                <div class="text-right" :style="{ width: '110px' }">
                  <router-link class="href" :to="{ name: '竞赛' }"
                    >查看更多</router-link
                  >
                </div>
              </div>
              <activityitem :activitys="getactivity.slice(0, 5)"></activityitem>
            </div>
          </div>
          <questionnumVue
            :teamid="teamid"
            :teamdata="teamdata2"
            :isshow="true"
            :getuser="user"
          ></questionnumVue>
          <div class="row m-0">
            <div class="col" :style="{ paddingLeft: '0px' }">
              <div class="my-home-div">
                <div class="my-home-div-line">
                  <i class="icon icon-ic_fluent_book_number_16_filled"></i>
                  最近练习题目
                </div>
                <div class="m-p-3 m-0">
                  <router-link
                    v-for="item in user.userquestion"
                    v-slot="{ navigate }"
                    custom
                    :to="{
                      name: '题目',
                      params: { ID: item.question?.ID },
                    }"
                  >
                    <div
                      class="jhfontweight cu home-item position-relative"
                      @click="navigate"
                      :span="11"
                      v-if="user"
                      :style="{ marginLeft: '6px' }"
                    >
                      <span>
                        {{ item.question?.name }}
                      </span>
                      <div
                        class="position-absolute top-0"
                        :style="{ right: '12px' }"
                      >
                        <i
                          class="icon icon-ic_fluent_arrow_circle_right_24_filled"
                          :style="{ color: 'var(--color-cheng)' }"
                        ></i>
                      </div>
                    </div>
                  </router-link>
                </div>
              </div>
            </div>
            <div class="col" :style="{ paddingRight: '0px' }">
              <div class="my-home-div">
                <div class="my-home-div-line position-relative">
                  <span>
                    <i class="icon icon-ic_fluent_clipboard_code_24_filled"></i>
                    能力测评
                  </span>
                  <div
                    class="position-absolute top-0"
                    :style="{
                      lineHeight: '47px',
                      fontSize: '14px',
                      right: '12px',
                    }"
                  >
                    <router-link
                      class="href"
                      :to="{ name: '题单', query: { purpose: '能力测评' } }"
                      >查看更多</router-link
                    >
                  </div>
                </div>
                <div class="m-p-3 m-0">
                  <router-link
                    v-for="v in 能力测评"
                    :key="`能力测评_${v.ID}`"
                    :to="{
                      name: '题库列表',
                      params: { ID: v.ID },
                      query: { istest: 1 },
                    }"
                    v-slot="{ navigate }"
                    custom
                  >
                    <div
                      class="jhfontweight cu home-item position-relative"
                      @click="navigate"
                    >
                      <span>{{ v.name }}</span>
                      <div
                        class="position-absolute top-0"
                        :style="{ right: '12px' }"
                      >
                        <i
                          class="icon icon-ic_fluent_arrow_circle_right_24_filled"
                          :style="{ color: 'var(--color-cheng)' }"
                        ></i>
                      </div>
                    </div>
                  </router-link>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="col">
          <signinactivityVue :user="user"></signinactivityVue>
          <div class="my-home-div">
            <div class="my-home-div-line">
              <i class="icon icon-ic_fluent_people_team_28_filled"></i> 我的团队
            </div>
            <div class="my-home-div-home-bgcolor">
              <el-container
                direction="vertical"
                :style="{ minHeight: '477px' }"
              >
                <el-main class="soet">
                  <h5 v-show="getteam.length == 0">您暂未加入团队</h5>
                  <el-select
                    class="select111"
                    v-model="teamid"
                    placeholder="请选择"
                    v-show="getteam.length"
                    filterable
                  >
                    <el-option
                      v-for="(v, i) in getteam"
                      :key="'team_' + i"
                      :label="v.name"
                      :value="Number(v.ID)"
                    >
                    </el-option>
                  </el-select>
                  <div v-show="acRank.length" class="rankmain">
                    <div class="runh row">
                      <div class="runh1">排名</div>
                      <div class="col text-center">用户名</div>
                      <div class="runh3">全AC题目数</div>
                      <div class="runh4">测试点得分率</div>
                    </div>
                    <div v-for="(d, k) in acRank" class="runkitem row">
                      <div class="runh1">
                        <strong>#{{ k + 1 }}</strong>
                      </div>
                      <div
                        class="col text-center text-wrap"
                        :title="d.name"
                        :style="{ fontSize: '12px' }"
                      >
                        <router-link
                          v-slot="{ href }"
                          custom
                          :to="{
                            name: '用户',
                            query: { userid: d.ID },
                          }"
                        >
                          <el-link :href="href">{{ d.name }} </el-link>
                        </router-link>
                      </div>
                      <div class="runh3">{{ d.ACcount || 0 }}</div>
                      <div class="runh4">{{ d.df || 0 }}%</div>
                    </div>
                  </div>
                </el-main>
                <el-footer
                  height="auto"
                  :style="{ '--el-footer-padding': '12px 12px' }"
                >
                  <el-row v-if="teamid && user">
                    <el-col
                      @click="
                        router.push({
                          name: '团队动态',
                          params: { ID: teamid },
                        })
                      "
                      :span="12"
                      :style="{
                        height: '112px',
                      }"
                      class="text-center"
                    >
                      <div
                        class="cu m-border-2 ztcolor fw-bold"
                        :style="{
                          height: '112px',
                          backgroundColor: '#FBE6E0',
                          marginRight: '6px',
                          fontSize: '14px',
                          paddingTop: '22px',
                          boxShadow:
                            '0px 0.3px 0.9px rgba(0, 0, 0, 0.05), 0px 1.6px 3.6px rgba(0, 0, 0, 0.06)',
                        }"
                      >
                        <div :style="{ marginBottom: '5px' }">
                          <img
                            src="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/jo_1_1_homepage/icon_oj_dongtai.svg"
                            class="shadow-joy-1 rounded-circle"
                          />
                        </div>
                        <div>团队动态</div>
                      </div>
                    </el-col>
                    <el-col :span="12" :style="{ minHeight: '60px' }">
                      <div
                        :style="{
                          height: '50px',
                          backgroundColor: '#FFF1E6',
                          lineHeight: '50px',
                          marginLeft: '6px',
                          fontSize: '14px',
                          boxShadow:
                            '0px 0.3px 0.9px rgba(0, 0, 0, 0.05), 0px 1.6px 3.6px rgba(0, 0, 0, 0.06)',
                        }"
                        class="text-center m-mb-3 cu m-border-2 ztcolor fw-bold"
                        @click="
                          router.push({
                            name: '团队题单',
                            params: { ID: teamid },
                          })
                        "
                      >
                        <img
                          src="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/jo_1_1_homepage/icon_oj_tuanduitidan.svg"
                          class="shadow-joy-2 rounded-circle"
                        />
                        &nbsp; 团队题单
                      </div>
                      <div
                        :style="{
                          height: '50px',
                          backgroundColor: '#DBE3FF',
                          lineHeight: '50px',
                          fontSize: '14px',
                          marginLeft: '6px',
                          boxShadow:
                            '0px 0.3px 0.9px rgba(0, 0, 0, 0.05), 0px 1.6px 3.6px rgba(0, 0, 0, 0.06)',
                        }"
                        class="text-center cu m-border-2 ztcolor fw-bold"
                        @click="
                          router.push({
                            name: '团队题目',
                            params: { ID: teamid },
                          })
                        "
                      >
                        <img
                          src="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/jo_1_1_homepage/icon_oj_tuanduitimu.svg"
                          class="shadow-joy-3 rounded-circle"
                        />
                        &nbsp; 团队题目
                      </div>
                    </el-col>
                    <el-col
                      :span="24"
                      v-if="
                        user &&
                        getteam.find(
                          (v) =>
                            (v.ID === teamid && v.userid === user.ID) ||
                            v.teamuser?.find((z) => z.userid === user.ID)
                              ?.isAdmin
                        )
                      "
                      :style="{
                        height: '50px',
                        backgroundColor: '#F5F5F5',
                        lineHeight: '50px',
                        fontSize: '14px',
                        marginTop: '12px',
                        boxShadow:
                          '0px 0.3px 0.9px rgba(0, 0, 0, 0.05), 0px 1.6px 3.6px rgba(0, 0, 0, 0.06)',
                      }"
                      class="text-center cu m-border-2 ztcolor fw-bold"
                      @click="
                        router.push({
                          name: '团队数据',
                          params: { ID: teamid },
                        })
                      "
                    >
                      <img
                        src="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/jo_1_1_homepage/icon_oj_tuanduishuju.svg"
                        class="shadow-joy-4 rounded-circle"
                      />
                      &nbsp; 团队数据
                    </el-col>
                  </el-row>
                </el-footer>
              </el-container>
            </div>
          </div>
          <integralnumVue :getuser="user"></integralnumVue>

          <!-- <div class="my-home-div" :style="{ marginTop: '24px', paddingBottom: '12px' }">
            <div class="my-home-div-line"> <i class="icon  icon-ic_fluent_news_16_filled"></i> {{
                data.banner?.update1?.name
            }}</div>
            <div v-if="data.banner?.update1?.list?.length">
              <div :style="{ lineHeight: '48px', paddingLeft: '24px' }" v-for="(v, i) in data.banner.update1.list"
                :key="'a__a' + i">
                <el-link target="_bank" :style="{ '--el-link-default-text-color': 'var(--color-22)', fontSize: '14px' }"
                  :underline="false" :href="v.url">
                  {{ v.name }}
                </el-link>
              </div>
            </div>
          </div> -->

          <div
            class="my-home-div"
            v-for="(vo, i) in data.banner.option"
            :style="{
              marginTop: '24px',
              paddingBottom: '12px',
              minHeight: '380px',
            }"
          >
            <div class="my-home-div-line row">
              <div class="col">
                <i
                  class="icon icon-ic_fluent_notebook_question_mark_24_filled"
                ></i>
                {{ vo.name }}
              </div>
            </div>
            <div
              class="home-item jhfontweight"
              v-for="(v, i) in vo.list"
              :key="'a__a' + i"
            >
              <el-link
                target="_bank"
                :style="{ '--el-link-default-text-color': 'var(--color-22)' }"
                :underline="false"
                :href="v.url"
              >
                {{ v.name }}
              </el-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, onMounted, ref } from "vue";
import {
  asyncgetmyquestion,
  asyncgetmyquestionbank,
  asyncgetsetup,
  asyncranking,
  asyncselectchart,
  asyncselectquestionbank,
  asyncteamuserquestion,
} from "../../api";
import activityitem from "../../components/activity/listmenu2.vue";
import integralnumVue from "./User/integralnum.vue";
import questionnumVue from "./User/questionnum.vue";
import signinactivityVue from "./home/signinactivity.vue";

import { useStorage } from "@vueuse/core";
import { dayjs } from "element-plus";
import { reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Storekey } from "../../interface";
import Studycodemodel from "../../mysql_interface/studycodemodel";

// 码客行
const tenant_id = inject<string | undefined>("tenant_id", undefined);

const dayMs = 3600 * 1000 * 24;

const props = defineProps<{ changeTeam: Function }>();

const router = useRouter();
const data = reactive<Studycodemodel.Isetup>({
  banner: {},
});
const color = [
  "#B83914",
  "#CF4017",
  "#EC4313",
  "#EB6C47",
  "#EE8263",
  "#FF8461",
  "#FF9C80",
  "#FFB099",
  "#FFC3B2",
  "#FFD7CC",
  "#FFEBE5",
];

const acRank = ref<
  {
    ID?: number;
    name?: string;
    ACcount?: number;
    df?: number;
    headportrait?: string;
  }[]
>([]);
const teamdata2 = ref<{
  ID?: number;
  name?: string;
  ACcount?: number;
  df?: number;
  headportrait?: string;
}>({});
async function teamstart2(teamid: number) {
  if (teamid && store.state.user?.ID) {
    try {
      const t = await asyncranking({
        teamid: teamid,
        userid: store.state.user?.ID,
        formdate: Date.now() - dayMs * 365,
        todate: dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss"),
      });
      const [data] = t.ACrank.map((e) => {
        const user = t.user.find((z) => z.ID === e.userid);
        return {
          ...e,
          ...user,
          ACcount: e.count,
          df: Math.floor(
            (Number(e.resultdataarrlength) / Number(e.resultdataarraclength)) *
              100
          ),
        };
      });
      teamdata2.value = data;
    } catch (e) {
      // ElMessage.error('没有查询')
    }
  }
}

const data3 = ref<{ name: string; count: number; color: string }[]>([]);
const data5 = ref<{ name: string; count: number }[]>([]);
async function teamstart() {
  if (teamid.value) {
    try {
      const t = await asyncranking({
        teamid: teamid.value,
        formdate: dayjs(Date.now() - dayMs * 30).format("YYYY-MM-DD 00:00:00"),
        todate: dayjs(new Date()).format("YYYY-MM-DD 23:59:59"),
      });
      acRank.value = t.user
        .map((e) => {
          const userRankInfo = t.ACrank.find((z) => z.userid === e.ID);
          return {
            ...e,
            ...userRankInfo,
            ACcount: userRankInfo?.count || 0,
            df: Math.floor(
              (Number(userRankInfo?.resultdataarrlength) /
                Number(userRankInfo?.resultdataarraclength)) *
                100
            ),
          };
        })
        .sort((a, b) => {
          return b.df - a.df;
        })
        .sort((a, b) => {
          return b.ACcount - a.ACcount;
        })
        .slice(0, 10);
    } catch (e) {
      // ElMessage.error('没有查询')
    }
  }
}

const myquestion = ref<Studycodemodel.Iquestion[]>([]);
const myquestionbank = ref<Studycodemodel.Iquestionbank[]>([]);
// 默认从localStorage取
const myteam = useStorage<Studycodemodel.Iteam>("my-team", { color: "-cheng" });
// const teamid = computed(() => {
//   return myteam.value?.ID
// })
const teamid = computed({
  get: () => {
    console.log("home.vue teamid computed", myteam.value?.ID);
    return myteam.value?.ID;
  },
  set: (v) => {
    const currTeam = getteam.value.find((t) => t.ID == v);
    console.log("home.vue teamid watch currTeam", v, currTeam);
    props.changeTeam(currTeam);
  },
});
watch(
  () => teamid.value,
  (v) => {
    teamstart();
    startchar();
    //
    // const currTeam = getteam.value.find(t => t.ID == v)
    // console.log("home.vue teamid watch currTeam", v, currTeam)
    // props.changeTeam(currTeam)
  }
);

const store = useStore(Storekey);
const user = computed(() => {
  return store.state.user || {};
});
const getactivity = computed(() => {
  return store.state.activity?.rows || [];
});
const getteam = computed(() => {
  return store.state.team?.rows || [];
});

const 赛前集训 = ref<Studycodemodel.Iquestionbank[]>([]);
const 能力测评 = ref<Studycodemodel.Iquestionbank[]>([]);

// watch(() => getteam.value, (v) => {
//   if (v.length) {
//     teamid.value = v[0].ID;
//   }
// })

onMounted(async () => {
  start();
  startchar();
  //
  teamstart();
});

async function start() {
  const { banner = {} } = await asyncgetsetup();
  data.banner = banner;
  store.dispatch("actionactivity", {
    tenant_id, // 码客行
    _limit: 5,
  });
  store.dispatch("actionquestion", {
    _limit: 5,
    _order: "ID",
    _sortable: "DESC",
  });

  if (user.value.ID) {
    const { rows } = await asyncgetmyquestion({
      _limit: 5,
      _offset: 0,
      _order: "ID",
    });

    myquestion.value = rows;
    const data = await asyncgetmyquestionbank({
      _limit: 5,
      _offset: 0,
      _order: "ID",
    });
    myquestionbank.value = data.rows;
  }
  if (getteam.value.length) {
    // teamid.value = Number(getteam.value[0].ID);
    teamstart2(teamid.value!);
  }
  const questionbank_1 = await asyncselectquestionbank({
    _limit: 15,
    _offset: 0,
    _order: "top",
    purpose: "能力测评",
    _sortable: "ASC",
  });
  const questionbank_2 = await asyncselectquestionbank({
    _limit: 5,
    _offset: 0,
    _order: "top",
    purpose: "赛前集训",
    _sortable: "ASC",
    teamid: {
      or: {
        is: null,
        in: [...getteam.value.map((e) => e.ID)],
      },
    },
    usertype: ["public", "team"],
  });
  赛前集训.value = questionbank_2.rows;
  能力测评.value = questionbank_1.rows;
}

const getlabel = computed(() => {
  return store.state.label?.rows || [];
});

async function startchar() {
  if (user.value.ID && teamid.value) {
    try {
      const t = await asyncteamuserquestion({
        teamid: teamid.value,
        todate: new Date(),
        formdate: Date.now() - 1000 * 60 * 60 * 24 * 365,
        userid: user.value.ID,
      });
      data3.value = t.AClabel.sort((a, b) => b.count - a.count).map<{
        name: string;
        count: number;
        color: string;
      }>((e, k) => {
        return {
          name: getlabel.value.find((t) => t.ID === e.labelid)?.name as string,
          count: e.count,
          color: color[k] ? color[k] : "#D9D9D9",
        };
      });
    } catch (e) {}

    asyncselectchart({
      starttime: Date.now() - 1000 * 60 * 60 * 24 * 365,
      endtime: Date.now(),
      timetype: "%Y-%m月",
      userids: [user.value.ID],
      teamid: teamid.value,
    })
      .then((f) => {
        data5.value = f.userquestion.map((e) => {
          return {
            name: e.day,
            count: e.count,
          };
        });
      })
      .catch(() => {});
  }
}

watch(
  () => user.value,
  async (v) => {
    if (v) {
      const { rows } = await asyncgetmyquestion({
        _limit: 5,
        _offset: 0,
        _order: "ID",
      });
      myquestion.value = rows;
      const data = await asyncgetmyquestionbank({
        _limit: 5,
        _offset: 0,
        _order: "ID",
      });
      myquestionbank.value = data.rows;
      startchar();
    }
  }
);
</script>

<style scoped>
#home {
  padding-top: 30px;
  color: var(--color-22);
}

#home h5 span {
  font-size: 16px;
}

#home {
  margin-bottom: 20px;
  padding-bottom: 40px;
  background-color: var(--color-fa);
}

.home-item {
  background: rgba(255, 255, 255, 0.5);
  font-size: 14px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 2px;
}

.home-item a {
  display: block;
}

.home-item:hover {
  background-color: var(--color-f5);
  color: var(--color-cheng);
}

.home-item-input {
  border-width: 1px;
}

.home-item-input:focus-visible {
  border-color: var(--color-cheng) !important;
}

.input-with-select {
  height: 28px;
  width: 264px;
}

.soet {
  height: 100%;
  --el-main-padding: 12px;
}

.soet::-webkit-scrollbar {
  width: 0;
}

.href {
  text-decoration: none;
  color: var(--color-cheng);
  font-size: 14px;
  font-weight: 400;
}

.href1 {
  text-decoration: none;
  color: #fff;
}

h2 {
  font-weight: 700;
  margin-bottom: 24px;
  font-size: 24px;
}

.select111 {
  display: block;
  margin-bottom: 12px;
  --el-input-border-color: rgba(0, 0, 0, 0.06);
}

.shadow-joy-1 {
  box-shadow: 0px 4px 10px rgba(235, 125, 93, 0.32);
}

.shadow-joy-2 {
  box-shadow: 0px 4px 10px rgba(255, 131, 0, 0.16);
}

.shadow-joy-3 {
  box-shadow: 0px 4px 10px rgba(72, 113, 255, 0.32);
}

.shadow-joy-4 {
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.18);
}

h5 {
  font-weight: 400;
}

.my-home-div-line i {
  font-size: 16px;
}

.my-home-div-home-bgcolor {
  background-color: rgba(255, 255, 255, 0.5);
}

.rankmain {
  border: 1px solid rgba(0, 0, 0, 0.06);
  box-sizing: border-box;
  border-radius: 2px;
  padding: 0px;
  font-size: 14px;
  margin-top: 12px;
  margin-bottom: 12px;
  margin: 0;
  padding: 12px;
}

.rankmain .row {
  margin: 0;
  line-height: 28px;
  margin-bottom: 12px;
  height: 28px;
  overflow: hidden;
}

.runh div {
  display: inline-block;
  font-weight: bold;
  padding: 0;
}

.runh1 {
  width: 44px;
  text-align: center;
}

.runh2 {
  width: 88px;
}

.rankmain a {
  text-decoration: none;
  color: var(--color-22);
}

.runh2 a:hover {
  text-decoration: none;
  color: var(--color-cheng);
}

.runh3 {
  width: 88px;
  text-align: center;
}

.runh4 {
  width: 88px;
  text-align: center;
}

.jhfontweight {
  height: 44px;
  margin: 12px;
  line-height: 44px;
  margin-bottom: 0px;
  padding-left: 12px;
  padding-right: 12px;
  font-size: 14px;
  overflow: hidden;
}

.jhfontweight span {
  width: 260px;
  overflow: hidden;
  display: inline-block;
}

.char {
  padding-top: 24px;
  font-size: 18px;
  color: var(--color-43);
  text-align: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.text-wrap {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 104px;
}
</style>

<style>
#home .col-xl-8 {
  padding: 0;
  overflow: hidden;
}

#home .el-carousel__container {
  height: 176px;
}

#home .myel-calendar .el-button span {
  display: inline-block;
  width: 12px;
  overflow: hidden;
}

#home .myel-calendar thead {
  display: none;
}

#home .myel-calendar .el-calendar__body {
  padding: 0;
}

#home .myel-calendar .el-calendar__body .el-calendar-table td {
  border: none;
}

#home .el-calendar__header {
  border: none;
  padding-top: 0px;
  padding-left: 8px;
  padding-bottom: 0px;
  padding-right: 4px;
}

#home .myel-calendar .el-calendar__body .el-calendar-table .el-calendar-day {
  height: 30px;
  padding: 2px;
  text-align: center;
}

#home .el-calendar__body {
  font-size: 12px;
  line-height: 26px;
}

#home .el-tabs__header {
  margin: 0;
  height: 48px;
  line-height: 47px;
  font-size: 16px;
}

#home .el-tabs__nav {
  padding-left: 14px;
  padding-right: 14px;
}

#home .el-tabs__header {
  --el-border-color-light: rgba(117, 117, 117, 0.4);
}
</style>
